import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_crop/image_crop.dart';

// ignore: must_be_immutable
class ImgCrop extends StatefulWidget {
  ImgCrop(this.image);

  File image; //原始图片路径

  @override
  _ImgCropState createState() => new _ImgCropState();
}

class _ImgCropState extends State<ImgCrop> {
  double baseLeft; //图片左上角的x坐标
  double baseTop; //图片左上角的y坐标
  double imageWidth; //图片宽度，缩放后会变化
  double imageScale = 1; //图片缩放比例
  Image imageView;
  final cropKey = GlobalKey<CropState>();

  double screenHeight; // 屏幕高度
  double screenWidth; // 屏幕宽度

  /// 初始化屏幕信息
  void _initScreen(context) {
    if (screenHeight == null) {
      screenHeight = MediaQuery.of(context).size.height;
      screenWidth = MediaQuery.of(context).size.width;
    }
  }

  @override
  Widget build(BuildContext context) {
    _initScreen(context);
    return Scaffold(
        body: Container(
      height: screenHeight,
      width: screenWidth,
      color: Color(0xff333333),
      child: Column(
        children: <Widget>[
          Container(
            height: screenHeight * 0.8,
            child: Crop.file(
              widget.image,
              key: cropKey,
              aspectRatio: 1.0,
              alwaysShowGrid: false,
            ),
          ),
          RaisedButton(
            onPressed: () {
              _crop(widget.image);
            },
            child: Text('完成'),
          ),
        ],
      ),
    ));
  }

  Future<void> _crop(File originalFile) async {
    final crop = cropKey.currentState;
    final area = crop.area;
    if (area == null) {
      //裁剪结果为空
      Navigator.pop(context, '裁剪失败');
    }
    await ImageCrop.requestPermissions().then((value) {
      if (value) {
        ImageCrop.cropImage(
          file: originalFile,
          area: crop.area,
        ).then((file) {
          Navigator.pop(context, file);
        }).catchError((err) {
          Navigator.pop(context, '裁剪错误');
          return null;
        });
      } else {
        Navigator.pop(context, '获取权限失败');
      }
    });
  }
}
